package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.account.UserAccount;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

	@Autowired
	private UserAccountMapper userAccountMapper;

	/**
	 * 获取账户的可用金额
	 *
	 * @param userId
	 * @return
	 */
	@Override
	public BigDecimal getAvailableAmount(Long userId) {
		//查询用户的账户
		UserAccount userAccount =
				userAccountMapper.selectOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId, userId));
		if (userAccount == null){
			//账户不存在,初始化账户
			Integer i = initAccount(userId);
			if (i <=0 ){
				throw new GuiguException(201,"初始化账户失败");
			}
			//返回可用金额
			return new BigDecimal(0);
		}
		//存在则返回可用金额
		return userAccount.getAvailableAmount();
	}

	/**
	 * 初始化账户
	 *
	 * @param userId
	 * @return
	 */
	@Override
	public Integer initAccount(Long userId) {
		UserAccount userAccount = new UserAccount();
		userAccount.setUserId(userId);
		BigDecimal bigDecimal = new BigDecimal(0);
		userAccount.setTotalPayAmount(bigDecimal);
		userAccount.setAvailableAmount(bigDecimal);
		userAccount.setTotalIncomeAmount(bigDecimal);
		userAccount.setTotalAmount(bigDecimal);
		userAccount.setLockAmount(bigDecimal);
		//保存账户
		return userAccountMapper.insert(userAccount);
	}
}
